<template>
  <el-dialog
    :title="formType === 'add' ? '新增班级' : '编辑班级'"
    v-model="dialogVisible"
    width="650px"
    @close="handleClose"
    top="5vh"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="right"
      class="class-form"
    >
      <el-form-item label="班级号" prop="classNo">
        <el-input v-model="form.classNo" placeholder="请输入班级号" clearable />
      </el-form-item>

      <el-form-item label="班主任姓名" prop="teacherFullName">
        <el-input
          v-model="form.teacherFullName"
          placeholder="请输入班主任姓名"
          clearable
        />
      </el-form-item>

      <el-form-item label="所属专业" prop="mayjorName">
        <el-input
          v-model="form.mayjorName"
          placeholder="请输入所属专业"
          clearable
        />
      </el-form-item>

      <el-form-item label="所属学院" prop="collegeName">
        <el-input
          v-model="form.collegeName"
          placeholder="请输入所属学院"
          clearable
        />
      </el-form-item>

      <el-form-item label="入学年份" prop="enrollmentYear">
        <el-input
          v-model="form.enrollmentYear"
          placeholder="请输入入学年份，如2023"
          clearable
        />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入班级描述"
          :rows="3"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="2"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting"
          >提交</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import classApi from "@/api/class";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  formType: {
    type: String,
    default: "add", // 'add' 或 'edit'
  },
  classData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:modelValue", "submit-success"]);

// 对话框可见性
const dialogVisible = ref(props.modelValue);

// 表单引用，用于表单验证
const formRef = ref(null);

// 提交状态
const submitting = ref(false);

// 表单数据
const form = reactive({
  id: undefined,
  classNo: "",
  teacherId: "",
  teacherFullName: "",
  mayjorId: undefined,
  mayjorName: "",
  collegeId: undefined,
  collegeName: "",
  enrollmentYear: "",
  description: "",
  remark: "",
});

// 表单验证规则
const rules = {
  classNo: [
    { required: true, message: "请输入班级号", trigger: "blur" },
    { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" },
  ],
  teacherFullName: [
    { required: false, message: "请输入班主任姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  enrollmentYear: [
    { required: false, message: "请输入入学年份", trigger: "blur" },
    {
      pattern: /^\d{4}$/,
      message: "请输入有效的年份，如2023",
      trigger: "blur",
    },
  ],
};

// 监听对话框可见性的变化
watch(
  () => props.modelValue,
  (value) => {
    dialogVisible.value = value;
  }
);

// 监听对话框内部可见性的变化
watch(
  () => dialogVisible.value,
  (value) => {
    emit("update:modelValue", value);
  }
);

// 监听外部传入的班级数据变化
watch(
  () => props.classData,
  (newVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      // 将外部传入的数据复制到表单中
      Object.assign(form, newVal);
    }
  },
  { immediate: true, deep: true }
);

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }

  // 手动清空表单数据
  form.id = undefined;
  form.classNo = "";
  form.teacherId = "";
  form.teacherFullName = "";
  form.mayjorId = undefined;
  form.mayjorName = "";
  form.collegeId = undefined;
  form.collegeName = "";
  form.enrollmentYear = "";
  form.description = "";
  form.remark = "";
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.error("表单验证失败:", fields);
      return;
    }

    submitting.value = true;
    try {
      if (props.formType === "add") {
        // 新增班级
        await classApi.createClass(form);
        ElMessage.success("添加成功");
      } else {
        // 编辑班级
        await classApi.updateClass(form);
        ElMessage.success("更新成功");
      }

      // 关闭对话框并通知父组件刷新数据
      dialogVisible.value = false;
      emit("submit-success");
      resetForm();
    } catch (error) {
      console.error("提交表单失败:", error);
      ElMessage.error(`提交失败: ${error.message || "未知错误"}`);
    } finally {
      submitting.value = false;
    }
  });
};
</script>

<style scoped>
.class-form {
  max-height: 65vh;
  overflow-y: auto;
  padding-right: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
